<?php

namespace backend\controllers;
use Yii;
use backend\models\Admin_node;
use yii\data\Pagination;

/*
*权限管理
 */
class NodeController extends \yii\web\Controller
{
	public $layout = 'admin_main';
    function init()
    {
        $session = Yii::$app->session;
        if(empty($session->get('admin_user')))
        {
            $this->redirect('?w=login/login');
        }
    }
	//展示权限
    public function actionNode_lists()
    {
    	$model = Admin_node::find();
    	$Page = new Pagination([
            'defaultPageSize' => 7,
            'totalCount' => $model->count(),
        ]);
    	$data = $model
    				->offset($Page->offset)
    				->limit($Page->limit)
    				->all();
    	$nowPage = Yii::$app->request->get('page') ? Yii::$app->request->get('page') : 1;
    	$NodeForm = new Admin_node;
    	return $this->render('node',
            ['nodeDate'=>$data,
            'page'=>$Page,
            'nowPage'=>$nowPage,
            'NodeForm'=> $NodeForm
            ]);
    }

    //添加权限
    public function actionAdd_node()
    {
    	$model = new Admin_node();

    	if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {

            return $this->redirect($_SERVER['HTTP_REFERER']);
    	}
    	else
    	{
    		exit('添加失败!!');
    	}
    }

    //修改权限
    public function actionNode_update()
    {
        $id = Yii::$app->request->post('id') ? Yii::$app->request->post('id') : 0;
    	$model = Admin_node::findOne($id);

    	if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {
            
            return $this->redirect(['node_lists']);
    	}
    	else
    	{
    		exit('修改失败!!');
    	}
    }

    //删除权限
    public function actionNode_delete()
    {
        $id = Yii::$app->request->post('node_id') ? Yii::$app->request->post('node_id') : 1;
        $node = Admin_node::findOne($id);
        if($node->delete())
        {
            $json['error'] = true;
            $json['msg']   = "删除成功";
        }
        else
        {
            $json['error'] = false;
            $json['msg']   = "删除失败";
            
        }
        return json_encode($json);
    }

    //查询单条
    public function actionFindone()
    {
        $id = Yii::$app->request->post('id') ? Yii::$app->request->post('id') : '';
        $obj = Admin_node::findOne($id);
        if(is_object($obj) && $id != ''){
            //把对象转换为数组
            $data = $this->obj2Arr($obj);
            $json['error'] = true;
            $json['msg']   = $data;
        }else{

            $json['error'] = false;
            $json['msg']   = '该条数据错误';
        }
        return json_encode($json);
    }

    //对象转换为数组
    public function obj2Arr($obj)
    {
        $arr = [];
        if (is_object($obj)) {
            foreach ($obj as $k => $v) {
                $arr[$k] = $v; 
            }
        }
        else
        {
            $arr = $obj;
        }
        return $arr;
    }
}
